//
//  MainViewController.m
//  Ufan
//
//  Created by yangqingluo on 15/10/25.
//  Copyright © 2015年 yangqingluo. All rights reserved.
//

#import "MainViewController.h"
#import "MainProductCell.h"
#import "MainProductSellCell.h"
#import "AccountViewController.h"
#import "DropDownListView.h"
#import "DropDownChooseProtocol.h"
#import "ProductVC.h"
#import "MainProductCollectionCell.h"
#import "MainProductHeaderView.h"
#import "XHRefreshControl.h"

static NSString *identify = @"MainProductCollectionCell";

@interface MainViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UISearchBarDelegate, UISearchDisplayDelegate,DropDownChooseDelegate,DropDownChooseDataSource,XHRefreshControlDelegate>

@property (nonatomic, strong) UICollectionView *showCollectionView;
@property (nonatomic, strong) NSArray *showArray;


@property (nonatomic, strong) DropDownListView *dropDownView;
@property (nonatomic, strong) NSArray *menuArray;

@property (nonatomic, strong) XHRefreshControl *refreshControl;

@property (nonatomic, strong) NSMutableArray *searchArray;
@property (strong, nonatomic) UISearchBar *searchBar;
@property (strong, nonatomic) UISearchDisplayController *searchController;

@end

@implementation MainViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self searchController];
    self.searchBar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44);
    [self.view addSubview:self.searchBar];
    
    [self setupBarButtonItem];
    [self.view addSubview:self.showCollectionView];
    
    
    [self.refreshControl startPullDownRefreshing];
    
}

- (void)setupBarButtonItem{
    self.title = @"锦食";
    
//    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 64, 44)];
//    [backButton setImage:[UIImage imageNamed:@"nav_more.png"] forState:UIControlStateNormal];
//    [backButton setImageEdgeInsets:UIEdgeInsetsMake(7, 0, 7, 34)];
//    backButton.tag = 988;
//    [backButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
//    [self.navigationItem setLeftBarButtonItem:backItem];
    
    UIButton *saveButton = [[UIButton alloc] initWithFrame:CGRectMake(self.navigationController.navigationBar.bounds.size.width - 64, 0, 64, 44)];
    [saveButton setImage:[UIImage imageNamed:@"nav_account"] forState:UIControlStateNormal];
    saveButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    saveButton.tag = 989;
    [saveButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *saveItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    [self.navigationItem setRightBarButtonItem:saveItem];
}


-(void)buttonClick:(UIButton *)button{
    switch (button.tag) {
            //更多
        case 988:{
//            [[AppPublic shareInstanceApp].mainSlide showLeftView];
        }
            break;
            
            //添加
        case 989:{
            [self.navigationController pushViewController:[AccountViewController new] animated:YES];
        }
            break;
            
            
        default:
            
            break;
    }
    
    
}

- (void)refreshDataSource{
    [self getProductsWithPage:1 type:QKHTTP_ProductTypeAll shopID:@"" categoryID:nil];
}




#pragma getter
- (UICollectionView *)showCollectionView{
    if (!_showCollectionView) {
        UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        flowLayout.headerReferenceSize = CGSizeMake(self.view.width, 0);//头部
        
        _showCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 44,  self.view.width, self.view.height - STATUS_BAR_HEIGHT) collectionViewLayout:flowLayout];
        _showCollectionView.dataSource = self;
        _showCollectionView.delegate = self;
        _showCollectionView.backgroundColor = [UIColor clearColor];
        _showCollectionView.alwaysBounceVertical = YES;
        [_showCollectionView registerClass:[MainProductCollectionCell class] forCellWithReuseIdentifier:identify];
        [_showCollectionView registerClass:[MainProductHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MainProductHeader"];
    }
    
    
    return _showCollectionView;
}


- (XHRefreshControl *)refreshControl{
    if (!_refreshControl) {
        _refreshControl = [[XHRefreshControl alloc]initWithScrollView:self.showCollectionView delegate:self];
    }
    
    return _refreshControl;
}

- (DropDownListView *)dropDownView{
    if (!_dropDownView) {
        _dropDownView = [[DropDownListView alloc] initWithFrame:CGRectMake(0 , 0, self.view.frame.size.width, 40) dataSource:self delegate:self];
        _dropDownView.backgroundColor = RGBA(245, 245, 245, 1.0);
        _dropDownView.mSuperView = self.view;
        
    }
    
    return _dropDownView;
}

- (NSArray *)menuArray{
    if (!_menuArray) {
        _menuArray = @[
                       @[@"全部分类",@"蛋糕甜点",@"川菜",@"西餐"],
                       @[@"全城",@"金牛区",@"青羊区"],
                       @[@"智能排序",@"好评优先",@"离我最近",@"人均最低"]
                       ];
    }
    
    return _menuArray;
}

- (NSMutableArray *)searchArray{
    if (!_searchArray) {
        _searchArray = [NSMutableArray new];
    }
    
    return _searchArray;
}

- (UISearchBar *)searchBar
{
    if (_searchBar == nil) {
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.delegate = self;
        _searchBar.placeholder = @"搜索";
        _searchBar.backgroundColor = [UIColor colorWithRed:0.747 green:0.756 blue:0.751 alpha:1.000];
    }
    
    return _searchBar;
}

- (UISearchDisplayController *)searchController{
    if (_searchController == nil) {
        _searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
        _searchController.delegate = self;
        _searchController.searchResultsTableView.dataSource = self;
        _searchController.searchResultsTableView.delegate = self;
        _searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    
    return _searchController;
}

#pragma mark refreshControl

/**
 *  1、这个是用于标识用户是否在加载数据中，所以涉及到业务逻辑的问题，所以就外部传值
 *
 *  @return 如果不实现该delegate方法，所有效果都会实现
 */
- (BOOL)isLoading{
    return NO;
}

/**
 *  2、将要开始下拉刷新的方法
 */
- (void)beginPullDownRefreshing{
    [self refreshDataSource];
}

/**
 *  3、将要开始上提加载更多的方法
 */
- (void)beginLoadMoreRefreshing{
//    [self refreshDataSource:currentPage + 1];
}

/**
 *  4、最后更新数据的时间
 *
 *  @return 返回缓存最后更新某个页面的时间
 */
- (NSDate *)lastUpdateTime{
    return nil;
}

/**
 *  1、是否支持下拉刷新
 *
 *  @return 如果没有实现该delegate方法，默认是支持下拉的，为YES
 */
- (BOOL)isPullDownRefreshed{
    return YES;
}

/**
 *  2、是否支持上提加载更多
 *
 *  @return 如果没有实现该delegate方法，默认是支持上提加载更多的，为YES
 */
- (BOOL)isLoadMoreRefreshed{
//    return currentPage <= pageCount;
    
    return NO;
}

/**
 *  3、标识下拉刷新是UIScrollView的子view，还是UIScrollView父view的子view
 *
 *  @return 如果没有实现该delegate方法，默认是scrollView的子View，为XHRefreshViewLayerTypeOnScrollViews
 */
- (XHRefreshViewLayerType)refreshViewLayerType{
    return XHRefreshViewLayerTypeOnScrollViews;
}

/**
 *  4、UIScrollView的控制器是否保留iOS7新的特性，意思是：tablView的内容是否可以穿透过导航条
 *
 *  @return 如果不是先该delegate方法，默认是不支持的
 */
- (BOOL)keepiOS7NewApiCharacter{
    return NO;
}

/**
 *  5、将自动加载更多的状态转换为手动加载需要的条件，现在是加载更多多少次后，开始转换
 *
 *  @return 如果不实现该delegate方法，默认是5次
 */
- (NSInteger)autoLoadMoreRefreshedCountConverManual{
    return 20;
}

- (void)endRefresh{
    if (self.refreshControl) {
        [self.refreshControl endPullDownRefreshing];
        [self.refreshControl endLoadMoreRefresing];
    }
}



#pragma mark -- dropDownListDelegate
-(void) chooseAtSection:(NSInteger)section index:(NSInteger)index
{
    NSLog(@"选了section:%ld ,index:%ld",(long)section,(long)index);
}

#pragma mark -- dropdownList DataSource
-(NSInteger)numberOfSections
{
    return [self.menuArray count];
}
-(NSInteger)numberOfRowsInSection:(NSInteger)section
{
    NSArray *arry = self.menuArray[section];
    return [arry count];
}
-(NSString *)titleInSection:(NSInteger)section index:(NSInteger) index
{
    return self.menuArray[section][index];
}
-(NSInteger)defaultShowSection:(NSInteger)section
{
    return 0;
}








#pragma mark - collection view delegate

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ProductVC *pVC = [[ProductVC alloc]initWithProductInfo:productInfoFormProduct(self.showArray[indexPath.row])];
    
    [self.navigationController pushViewController:pVC animated:YES];
}
#pragma mark - collection view datasource
//- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
//    return 1;
//}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.showArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MainProductCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    
    cell.product = [self.showArray objectAtIndex:indexPath.row];
    
    return cell;
}
//
//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
//    MainProductHeaderView *headView;
//    
//    if([kind isEqual:UICollectionElementKindSectionHeader]){
//        headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MainProductHeader" forIndexPath:indexPath];
//        [headView setBackgroundColor:[UIColor redColor]];
//    }
//
//    return headView;
//}

#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((collectionView.width - 30) / 2.0, (collectionView.width - 30)/ 2.0 + 20);
}
//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}
//定义每个UICollectionView 纵向的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    return CGSizeMake(self.view.width, 20);
//}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:self.searchController.searchResultsTableView]) {
        return self.searchArray.count;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.searchController.searchResultsTableView]) {
        static NSString *CellIdentifier = @"MainProductCell";
        MainProductCell *cell = (MainProductCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (cell == nil) {
            cell = [[MainProductCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.product = self.searchArray[indexPath.row];
        
        return cell;
    }
    
    
    return [UITableViewCell new];
}


#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.searchController.searchResultsTableView]) {
        return [MainProductCell tableView:tableView heightForRowAtIndexPath:indexPath];
    }
    return 0;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.searchController.searchResultsTableView]) {
        [self.searchController setActive:NO animated:NO];
        
        ProductVC *pVC = [[ProductVC alloc]initWithProductInfo:productInfoFormProduct(self.searchArray[indexPath.row])];
        
        [self.navigationController pushViewController:pVC animated:YES];
        
        
    }
    
}

#pragma mark - UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:YES animated:YES];
    
    return YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    [self.searchArray removeAllObjects];
    
    for (UFProduct *product in self.showArray) {
        if([product.name rangeOfString:searchString options:NSCaseInsensitiveSearch].location!=NSNotFound){
            [self.searchArray addObject:product];
        }
    }
    
    
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @"";
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:YES];
}



#pragma http
- (void)getProductsWithPage:(NSUInteger)pageNo type:(NSString *)type shopID:(NSString *)shopID categoryID:(NSString *)categoryID{
    
    [QKHttpManager getProductsWithPage:pageNo type:type shopID:shopID categoryID:categoryID completion:^(NSObject *object, NSError *error){
        [self endRefresh];
        if (!error) {
            if ([object isKindOfClass:[NSDictionary class]]) {
                if ([((NSDictionary *)object)[@"code"] intValue] == QKHTTP_SUCCESS) {
                    
                    self.showArray = productsFromArray(((NSDictionary *)object)[@"productList"]);
                    [self.showCollectionView reloadData];
                    
                    return;
                }
                else if ([((NSDictionary *)object)[@"code"] intValue] == QKHTTP_ERROR){
                    
                }
                
            }
        }
        
        [self showHint:httpRespString(error, object)];
        
    }];
}

@end
